#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 说明：onnx模式将纯中文文本转化为WAV语音。速度快。
import re,uuid
import sys,os,time
from infer import TTSExecutor
from paddlespeech.resource import CommonTaskResource
from flask import Flask, send_file, request, abort
app = Flask("__name__")

executor = TTSExecutor()
executor.task_resource = CommonTaskResource(task='tts', model_format='onnx')
executor._init_from_path_onnx(am='fastspeech2_csmsc',voc='hifigan_csmsc',lang='zh')

name = 'tmp'

@app.route("/api/tts", methods=["POST"])
def api_tts():
    text = request.form['text'].strip()
    try:
        st = time.time()
        executor.infer_onnx(text=text,lang='zh',am='fastspeech2_csmsc')
        global name
        if name != 'tmp':
            os.unlink(name)
        name = '/tmp/'+str(uuid.uuid1())+'.wav'
        executor.postprocess_onnx(name)
        dt = time.time()-st
        print("time cost: "+str(dt))
        return send_file(name)
    except:
        print(sys.exc_info())
        return abort(404)

if __name__ == '__main__':
    try:
        app.run(host="0.0.0.0", port=5000)
        if name != 'tmp':
            os.unlink(name)
    except:
        print("崩溃\n")
